package com.wn;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.UnknownFormatConversionException;
import java.util.concurrent.TimeUnit;

/**
 * @author yellow Docter
 * @date 2022 -09-05
 * @desc
 */
@RestController
@RequestMapping("order")
@Slf4j
public class Demo01Controller {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("test01")
    public String order(){

        // 【1. 获取锁的状态】 把锁的状态保存到redis中，谁能保存成功，谁就获取锁。key  goods:lock:100

        Boolean isLock =
                redisTemplate.opsForValue()
                        .setIfAbsent("goods:lock:100", "1", Duration.ofSeconds(30));

        if (!isLock){
            log.info("获取所失败...");
            return "failure";
        }
        try {

            //1. 从redis中获取库存
            Integer stock = Integer.parseInt(redisTemplate.opsForValue().get("goods:100"));
            if (stock > 0) {
                //2. 扣减库存
                stock--;
                //3. 更新redis
                redisTemplate.opsForValue().set("goods:100",String.valueOf(stock));
                //日志提示 扣减库存成功
                log.info("扣减库存成功,剩余：{}",stock);
                return "success";
            } else {
                return "failure";
            }
        }finally {
            //【3. 释放锁】
            redisTemplate.delete("goods:lock:100");
        }
    }

    @Autowired
    private RedissonClient redissonClient;

    public static final String ORDER_ID = "100100";

    @RequestMapping("test02")
    public String order2() throws InterruptedException {

        // 【1. 获取锁的状态】 把锁的状态保存到redis中，谁能保存成功，谁就获取锁。key  goods:lock:100
        RLock rLock = redissonClient.getLock(ORDER_ID);
        rLock.lock();

        try {

            //1. 从redis中获取库存
            Integer stock = Integer.parseInt(redisTemplate.opsForValue().get("goods:100"));
            if (stock > 0) {
                //2. 扣减库存
                stock--;
                //3. 更新redis
                redisTemplate.opsForValue().set("goods:100",String.valueOf(stock));
                //日志提示 扣减库存成功
                log.info("扣减库存成功,剩余：{}",stock);

            } else {
                return "failure";
            }
        }finally {
            //【3. 释放锁】
            rLock.unlock();
        }
        return "success";
    }

}

